local access = ngx.shared.access
local args = ngx.req.get_uri_args()  --获取参数
local count = args["count"] --获取个数
local host = args["host"]   --获取 主机地址
local status = args["status"]  --获取状态吗
local one_minute_ago = tonumber(os.date("%s")) - 60  --分钟前的事件错
local now = tonumber(os.date("%s"))  --现在的事件戳

local status_total = 0  ---统计的 状态个数
local flow_total = 0  --统计的流量相加
local reqt_total = 0   --统计的请求时间总数
local req_total = 0  ----。。。。。  请求的个数

if not host then   ---
    ngx.print("host arg not found.")
    ngx.exit(ngx.HTTP_OK)  ---报错
end

if count == "status" and not status then
    ngx.print("status arg not found.")
    ngx.exit(ngx.HTTP_OK)
end

if not (count == "status" or count == "flow" or count == "reqt") then
    ngx.print("count arg invalid.")
    ngx.exit(ngx.HTTP_OK)
end

for second_num=one_minute_ago,now do   ----统计从开始时间到现在的的每一秒 遍历  当然这个纬度还可以精确到分钟 以分钟的方式进行统计
    local flow_key = table.concat({host,"-flow-",second_num})
    local req_time_key = table.concat({host,"-reqt-",second_num})
    local total_req_key = table.concat({host,"-total_req-",second_num})

    if count == "status" then
        local status_key = table.concat({host,"-",status,"-",second_num})
        local status_sum = access:get(status_key) or 0
        status_total = status_total + status_sum
    elseif count == "flow" then
        local flow_sum = access:get(flow_key) or 0
        flow_total = flow_total + flow_sum
    elseif count == "reqt" then
        local req_sum = access:get(total_req_key) or 0
        local req_time_sum = access:get(req_time_key) or 0
        reqt_total = reqt_total + req_time_sum
        req_total = req_total + req_sum
    end
end

ngx.log(ngx.ERR," count "..count)

if count == "status" then
    ngx.print(status_total)
elseif count == "flow" then
    ngx.print(flow_total)
elseif count == "reqt" then
    local reqt_avg=0;

    ngx.log(ngx.ERR," req_total: "..req_total.." reqt_total:"..reqt_total)
    if req_total == 0 then
        reqt_avg = 0
    else
        reqt_avg = reqt_total/req_total
    end
    ngx.print(reqt_avg)

    ngx.print(reqt_total)

    ngx.print(req_total)
    ngx.log(ngx.ERR," "..req_total.." "..reqt_total)
end



